#!/usr/bin/env python3
"""
通用启动脚本 - Windows/Linux通用
使用方法: python run.py
"""

import os
import sys
import subprocess
import time
from pathlib import Path

def setup_environment():
    """设置环境"""
    # 获取项目根目录
    project_dir = Path(__file__).parent.absolute()
    os.chdir(project_dir)
    
    # 虚拟环境路径
    venv_path = project_dir / "venv"
    
    # 设置环境变量
    env = os.environ.copy()
    
    # 激活虚拟环境
    if venv_path.exists():
        if os.name == 'nt':  # Windows
            venv_scripts = venv_path / "Scripts"
            if venv_scripts.exists():
                env["PATH"] = f"{venv_scripts};{env.get('PATH', '')}"
                env["VIRTUAL_ENV"] = str(venv_path)
        else:  # Linux/Mac
            venv_bin = venv_path / "bin"
            if venv_bin.exists():
                env["PATH"] = f"{venv_bin}:{env.get('PATH', '')}"
                env["VIRTUAL_ENV"] = str(venv_path)
    
    return env, project_dir

def check_dependencies(env):
    """检查依赖"""
    # Windows使用uvicorn，Linux使用gunicorn
    if os.name == 'nt':  # Windows
        try:
            # 检查uvicorn
            result = subprocess.run(
                [sys.executable, "-m", "uvicorn", "--version"],
                env=env,
                capture_output=True,
                text=True
            )
            if result.returncode == 0:
                print(f"✅ Uvicorn版本: {result.stdout.strip()}")
                return True
        except Exception:
            pass
        
        print("❌ Uvicorn未安装，尝试安装...")
        try:
            subprocess.run(
                [sys.executable, "-m", "pip", "install", "uvicorn[standard]==0.24.0"],
                env=env,
                check=True
            )
            print("✅ Uvicorn安装成功")
            return True
        except subprocess.CalledProcessError:
            print("❌ Uvicorn安装失败")
            return False
    else:  # Linux/Mac
        try:
            # 检查gunicorn
            result = subprocess.run(
                ["gunicorn", "--version"],
                env=env,
                capture_output=True,
                text=True
            )
            if result.returncode == 0:
                print(f"✅ Gunicorn版本: {result.stdout.strip()}")
                return True
        except FileNotFoundError:
            pass
        
        print("❌ Gunicorn未安装，尝试安装...")
        try:
            subprocess.run(
                [sys.executable, "-m", "pip", "install", "gunicorn==21.2.0"],
                env=env,
                check=True
            )
            print("✅ Gunicorn安装成功")
            return True
        except subprocess.CalledProcessError:
            print("❌ Gunicorn安装失败")
            return False

def start_service(env, project_dir, daemon=False):
    """启动服务"""
    print("🚀 启动AI项目后端服务...")
    
    # 创建日志目录
    logs_dir = project_dir / "logs"
    logs_dir.mkdir(exist_ok=True)
    
    if os.name == 'nt':  # Windows - 使用uvicorn
        print("🪟 检测到Windows系统，使用Uvicorn启动")
        
        # Uvicorn启动参数
        uvicorn_args = [
            sys.executable, "-m", "uvicorn",
            "main:app",
            "--host", "0.0.0.0",
            "--port", "8000",
            "--reload" if not daemon else None,  # 开发模式启用热重载
            "--log-level", "info"
        ]
        uvicorn_args = [arg for arg in uvicorn_args if arg is not None]
        
        try:
            print("🌐 服务地址: http://localhost:8000")
            print("📚 API文档: http://localhost:8000/docs")
            if not daemon:
                print("按 Ctrl+C 停止服务")
            subprocess.run(uvicorn_args, env=env, cwd=project_dir)
            
        except KeyboardInterrupt:
            print("\n🛑 服务已停止")
        except Exception as e:
            print(f"❌ 启动失败: {e}")
            return False
            
    else:  # Linux/Mac - 使用gunicorn
        print("🐧 检测到Linux/Mac系统，使用Gunicorn启动")
        
        # Gunicorn启动参数
        gunicorn_args = [
            "gunicorn",
            "main:app",
            "-w", "4",
            "-k", "uvicorn.workers.UvicornWorker",
            "--bind", "0.0.0.0:8000",
            "--access-logfile", str(logs_dir / "access.log"),
            "--error-logfile", str(logs_dir / "error.log"),
            "--log-level", "info",
            "--max-requests", "1000",
            "--max-requests-jitter", "100",
            "--timeout", "120"
        ]
        
        if daemon:
            gunicorn_args.append("--daemon")
            gunicorn_args.extend(["--pid", str(project_dir / "gunicorn.pid")])
        
        try:
            if daemon:
                # 后台运行
                process = subprocess.Popen(
                    gunicorn_args,
                    env=env,
                    cwd=project_dir
                )
                time.sleep(3)
                
                # 检查PID文件
                pid_file = project_dir / "gunicorn.pid"
                if pid_file.exists():
                    pid = pid_file.read_text().strip()
                    print(f"✅ 服务启动成功！")
                    print(f"📊 进程ID: {pid}")
                    print(f"🌐 服务地址: http://localhost:8000")
                    print(f"📚 API文档: http://localhost:8000/docs")
                    return True
                else:
                    print("❌ 服务启动失败")
                    return False
            else:
                # 前台运行
                print("🌐 服务地址: http://localhost:8000")
                print("📚 API文档: http://localhost:8000/docs")
                print("按 Ctrl+C 停止服务")
                subprocess.run(gunicorn_args, env=env, cwd=project_dir)
                
        except KeyboardInterrupt:
            print("\n🛑 服务已停止")
        except Exception as e:
            print(f"❌ 启动失败: {e}")
            return False

def main():
    """主函数"""
    print("=" * 50)
    print("🚀 AI项目后端启动脚本")
    print("=" * 50)
    
    # 设置环境
    env, project_dir = setup_environment()
    print(f"📁 项目目录: {project_dir}")
    
    # 检查.env文件
    env_file = project_dir / ".env"
    if not env_file.exists():
        print("⚠️  警告: .env文件不存在，请确保已配置环境变量")
    
    # 检查依赖
    if not check_dependencies(env):
        print("❌ 依赖检查失败")
        sys.exit(1)
    
    # 选择启动模式
    if len(sys.argv) > 1 and sys.argv[1] == "--daemon":
        # 后台运行
        start_service(env, project_dir, daemon=True)
    else:
        # 前台运行（默认）
        print("💡 提示: 使用 'python run.py --daemon' 后台运行")
        start_service(env, project_dir, daemon=False)

if __name__ == "__main__":
    main() 